package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.UserHolder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    /**
     * 关注/取关
     * @param followUserId
     * @param isFloow
     * @return
     */
    @Override
    public Result follow(Long followUserId, Boolean isFloow) {
        // 1.获取当前用户
        UserDTO user = UserHolder.getUser();
        if (user == null){
            return Result.fail("未登录");
        }
        Long id = user.getId();
        Follow follow = new Follow();
        follow.setFollowUserId(followUserId);
        follow.setUserId(id);
        if (BooleanUtil.isTrue(isFloow)){
            // 关注
            // 存储到数据库
            follow.setCreateTime(LocalDateTime.now());
            save(follow);
        }else{
            // 取关
            Follow one = lambdaQuery().eq(Follow::getUserId, id)
                    .eq(Follow::getFollowUserId, followUserId).one();
            removeById(one);
        }

        return Result.ok();
    }

    /**
     * 判断是否关注
     * @param followUserId
     * @return
     */
    @Override
    public Result isFollow(Long followUserId) {
        // 1.获取当前用户
        UserDTO user = UserHolder.getUser();
        if (user == null){
            return Result.fail("未登录");
        }
        Long id = user.getId();
        Integer count = lambdaQuery().eq(Follow::getUserId, id)
                .eq(Follow::getFollowUserId, followUserId).count();
        return Result.ok(count > 0);
    }

    /**
     * 共同关注
     * @param followUserId
     * @return
     */
    @Override
    public Result followCommons(Long followUserId) {
        // 1.获取当前用户
        UserDTO user = UserHolder.getUser();
        if (user == null){
            return Result.fail("未登录");
        }
        Long id = user.getId();
        if (id.equals(followUserId)){
            return Result.fail("不能查看自己");
        }
        List<Follow> list = lambdaQuery()
                .or(q -> q.eq(Follow::getUserId, followUserId).eq(Follow::getFollowUserId, id))
                .or(q -> q.eq(Follow::getUserId, id).eq(Follow::getFollowUserId, followUserId))
                .list();
        return Result.ok(list.size()==2);
    }
}
